﻿using System;
using System.Net;
using System.Text;

namespace Firefly.ExtensionMethods
{
    public static class ByteArrayExtensions
    {
        public static byte[] TransposeBytesInWords(this byte[] obj)
        {
            if (obj.Length % 2 != 0)
            {
                throw new ArgumentException("Byte array must be even-sized");
            }

            int length = obj.Length;

            for (int i = 0; i < length; i += 2)
            {
                byte temp;
                temp = obj[i];
                obj[i] = obj[i + 1];
                obj[i + 1] = temp;
            }

            return obj;
        }

        public static string BigEndianByteBlockToLittleEndianString(this byte[] obj)
        {
            return (new UnicodeEncoding(true, false)).GetString(obj);
        }

        public static IPAddress HostOrderToIpAddress(this byte[] obj)
        {
            if (obj != null)
            {
                return new IPAddress(obj);
            }

            return IPAddress.None;
        }

        public static IPAddress NetworkOrderToIpAddress(this byte[] obj)
        {
            if (obj != null)
            {
                byte[] hoa = new byte[8];
                hoa[4] = obj[0];
                hoa[5] = obj[1];
                hoa[6] = obj[2];
                hoa[7] = obj[3];
                ulong no = (ulong)BitConverter.ToUInt64(hoa, 0);
                ulong ho = (ulong)IPAddress.NetworkToHostOrder((long)no);
                return new IPAddress((long)ho);
            }

            return IPAddress.None;
        }
    }
}